package com.woniuxy.health.customer.util;


import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.socket.TextMessage;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Map;

public class Myjob implements org.quartz.Job {

    private RedisTemplate redisTemplate;

    private SpringWebSocket springWebSocket;

    @Autowired
    public Myjob(RedisTemplate redisTemplate,SpringWebSocket webSocket){
        this.redisTemplate = redisTemplate;
        System.out.println("websocket地址:"+webSocket);
        this.springWebSocket = webSocket;
    }

    @SneakyThrows
    @Override
    /*统计各个时间段在线用户(定时器每天1个小时查询登录状态并记录下来,并以当天的日期+#LoginCount作为key存储)*/
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //判断redis是否存在该key,如果存在则计算该key的值并将其放入到redis的hashMap中
        //hashkey:日期+#LoginCount
        //key:时间点
        //value:该时间点对应的人数
        System.out.println("准备执行任务......");

        //默认count=0
        Long count = 0L;

        //判断LoginStatusKey是否存在
        String key = "LoginStatus#".concat(LocalDate.now().toString());
        if (redisTemplate.hasKey(key)) {
            //获得该整点统计的在线用户人数
            count = (Long)redisTemplate.execute(
                    (RedisCallback<Long>) connection ->
                            connection.bitCount(key.getBytes())
            );
        }

        //将统计数据放入到hashMap中进行处理
        redisTemplate.opsForHash().put("LoginCount#".concat(LocalDate.now().toString()), LocalTime.now().getHour()+"",String.valueOf(count));

        /*获取统计数据*/
        Map<String,Object> entries = redisTemplate.opsForHash().entries("LoginCount#".concat(LocalDate.now().toString()));

        //将该对象转换成json字符串
        String result = JSON.toJSONString(entries);

        //如果建立连接则通过websocket推送数据到前端,否则不推送...
        if (springWebSocket.getWebSocketSession() != null){
            System.out.println("准备推送数据......");
            springWebSocket.getWebSocketSession().sendMessage(new TextMessage(result));
            System.out.println("推送数据完成......");
        }
    }

}
